<template>
  <div v-loading="loading" class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="保养计划单号" prop="code">
          <CodeRuleInput :band-value.sync="formData.code" table-name="device_maintain_plan" column-name="code" :is-edit="id" />
        </el-form-item>
        <el-form-item />
        <el-form-item />
        <el-form-item label="保养设备" prop="bookId" class="clickChoose">
          <el-input v-if="!id" v-model="formData.bookName" placeholder="请选择" readonly />
          <!--          <el-select v-model="formData.bookId" clearable filterable placeholder="请选择">-->
          <!--            <el-option-->
          <!--              v-for="item in equipmentList"-->
          <!--              :key="item.id"-->
          <!--              :label="item.bookName"-->
          <!--              :value="item.id"-->
          <!--            />-->
          <!--          </el-select>-->
          <a v-if="!id" class="clickChoose_button" @click.prevent="chooseEquipments">
            <svg-icon icon-class="选择弹框" />
          </a>
          <el-input v-else v-model="formData.bookName" placeholder="保养设备" disabled />
        </el-form-item>
        <el-form-item label="保养模板" prop="templateId" class="clickChoose">

          <el-input v-model="formData.templateName" placeholder="请选择" readonly />
          <!--          <el-select v-model="formData.templateId" clearable filterable placeholder="请选择">-->
          <!--            <el-option-->
          <!--              v-for="item in templateList"-->
          <!--              :key="item.id"-->
          <!--              :label="item.code+'/'+item.name"-->
          <!--              :value="item.id"-->
          <!--            />-->
          <!--          </el-select>-->
          <a class="clickChoose_button" @click.prevent="chooseTemplates">
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="计划开始时间" prop="startTime">
          <div class="standing-add first">
            <div class="add-input">
              <el-date-picker
                v-model="formData.startTime"

                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                format="yyyy-MM-dd HH:mm"
                placeholder="请选择"
                :editable="false"
              />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="计划结束时间" prop="endTime">
          <div class="standing-add first">
            <div class="add-input">
              <el-date-picker
                v-model="formData.endTime"

                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                format="yyyy-MM-dd HH:mm"
                placeholder="请选择"
                :editable="false"
              />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="保养级别" prop="level">
          <el-select v-model="formData.level" clearable filterable placeholder="请选择">
            <el-option label="一级保养" :value="1" />
            <el-option label="二级保养" :value="2" />
            <el-option label="三级保养" :value="3" />
          </el-select>
        </el-form-item>
        <el-divider />
        <!-- <el-form-item label="下次保养时间" prop="nextTime">
          <div class="standing-add first">
            <div class="add-input">
              <el-date-picker
                v-model="formData.nextTime"

                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                format="yyyy-MM-dd HH:mm"
                placeholder="请选择"
                clearable
              />
            </div>
          </div>
        </el-form-item> -->
        <el-form-item label="任务启动方式" prop="taskMode">
          <el-select v-model="formData.taskMode" clearable filterable placeholder="请选择">
            <el-option label="上次任务开始后" :value="1" />
            <el-option label="上次任务完成后" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="保养周期" prop="period">
          <el-input-number
            v-model="formData.period"
            controls-position="right"
            class="numberComponents"
            :min="1"
          />
        </el-form-item>
        <el-form-item label="周期单位" prop="periodUnit">
          <el-select v-model="formData.periodUnit" clearable filterable placeholder="请选择">
            <!--                          <el-option label="分" value="分" />-->
            <el-option label="日" value="日" />
            <el-option label="周" value="周" />
            <el-option label="月" value="月" />
            <!--            <el-option label="季" value="季" />-->
            <!--            <el-option label="年" value="年" />-->
          </el-select>
        </el-form-item>
        <el-form-item label="任务提醒时间" prop="remind">
          <div class="number_input">
            <el-input-number
              v-model="formData.remind"
              controls-position="right"
              class="numberComponents"
              :min="0"
            />
            <div class="unit">日</div>
          </div>
        </el-form-item>
        <el-form-item label="合理逾期时间" prop="timeOutNumber">
          <div class="number_input">
            <el-input-number
              v-model="formData.timeOutNumber"
              controls-position="right"
              class="numberComponents"
              :min="0"
            />
            <div class="unit">日</div>
          </div>
        </el-form-item>
        <el-divider />
        <!-- <el-form-item label="维保班组" prop="maintenanceId">
          <el-select v-model="formData.maintenanceId" clearable filterable placeholder="请选择" @change="loadPeople">
            <el-option
              v-for="item in teamList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="保养人员" prop="maintainPersonId" class="clickChoose">

          <el-input v-model="formData.checkPersonName" placeholder="请选择" readonly />
          <!--          <el-select v-model="formData.maintainPersonId" clearable filterable placeholder="请选择" @change="searchTeam">-->
          <!--            <el-option-->
          <!--              v-for="item in peopleList"-->
          <!--              :key="item.userId"-->
          <!--              :label="item.realName"-->
          <!--              :value="item.userId"-->
          <!--            />-->
          <!--          </el-select>-->
          <a class="clickChoose_button" @click.prevent="chooseTeamAndPeople">
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="班次">
          <DictSelect :band-value.sync="formData.shiftCode" dict-type="shiftCode" />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            type="textarea"
            maxlength="200"
            show-word-limit
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="计划状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">持续执行</el-radio>
            <el-radio :label="0">暂停</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo } from '@/api/equipmentManage/equipmentMaintain/maintainPlan'
import { list } from '@/api/equipmentManage/equipmentMaintain/maintainTemplate'
import { list as getEquipmentList } from '@/api/equipmentManage/baseInfo/equipmentInfo'
import { list as maintenanceTeamList } from '@/api/equipmentManage/baseInfo/maintenanceTeam'
import { personnellist } from '@/api/equipmentManage/equipmentRepair/equipmentReportRepair'
import chooseTemplate from '../maintainTemplate/chooseTemplate.vue'
import chooseEquipment from '../../baseInfo/equipmentInfo/chooseEquiment.vue'
import chooseTeam from '../../baseInfo/maintenanceTeam/chooseTeam.vue'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {},
    isAdd: {}
  },
  data() {
    const validateStartTime = (rule, value, callback) => {
      // const startTime = this.formData.startTime
      // const endTime = this.formData.endTime
      this.$refs.form.clearValidate('endTime')
      // const nextTime = this.formData.nextTime
      if (this.formData.startTime > this.formData.endTime) {
        callback(new Error('计划开始时间不能超过计划结束时间'))
      } else if (!value) {
        callback(new Error('计划开始时间不能为空'))
      } else {
        callback()
      }
    }
    const validateEndTime = (rule, value, callback) => {
      // const startTime = this.formData.startTime
      // const endTime = this.formData.endTime
      if (this.formData.startTime) {
        this.$refs.form.clearValidate('startTime')
      }
      if (this.formData.startTime > this.formData.endTime) {
        callback(new Error('计划开始时间不能超过计划结束时间'))
      } else {
        callback()
      }
    }
    const validateNextTime = (rule, value, callback) => {
      const startTime = this.formData.startTime
      const endTime = this.formData.endTime
      const nextTime = this.formData.nextTime
      if (startTime && endTime && (nextTime > endTime || nextTime < startTime)) {
        callback(new Error('下次保养时间需要在计划时间范围内'))
      } else if (startTime && !endTime && nextTime < startTime) {
        callback(new Error('下次保养时间需要大于计划开始时间'))
      } else if (!startTime && endTime && nextTime > endTime) {
        callback(new Error('下次保养时间不能超过计划结束时间'))
      } else if (!value) {
        callback(new Error('下次保养时间不能为空'))
      } else {
        callback()
      }
    }
    const period = (rule, value, callback) => {
      if (!value) {
        callback(new Error('保养周期不能为空'))
      } else if (!this.SETTINGS.reg_integer.test(value)) {
        callback(new Error('保养周期只能为整数'))
      } else {
        callback()
      }
    }
    const remind = (rule, value, callback) => {
      if (value && !this.SETTINGS.reg_integer.test(value)) {
        callback(new Error('任务提醒时间只能为整数'))
      } else {
        callback()
      }
    }
    const timeOutNumber = (rule, value, callback) => {
      if (value && !this.SETTINGS.reg_integer.test(value)) {
        callback(new Error('合理逾期时间只能为整数'))
      } else {
        callback()
      }
    }
    return {
      loading: true,
      isShow: false,
      formData: {
        code: undefined,
        bookId: undefined,
        templateId: undefined,
        templateName: undefined,
        startTime: undefined,
        endTime: undefined,
        nextTime: undefined,
        taskMode: '',
        period: 1,
        bookName: '',
        periodUnit: '',
        maintenanceId: undefined,
        maintainPersonId: undefined,
        checkPersonName: '',
        shiftCode: '',
        status: 1,
        remark: undefined,
        remind: '0',
        level: '',
        timeOutNumber: '0',
        id: undefined
      },
      maxNumber: 99999,
      equipmentList: [],
      templateList: [],
      teamList: [],
      peopleList: [],
      num: 1,
      roleOptions: [],
      rules: {
        code: [
          { required: true, message: '保养计划单号不能为空', trigger: 'blur' }
        ],
        bookId: [
          { required: true, message: '保养设备不能为空', trigger: 'change' }
        ],
        templateId: [
          { required: true, message: '保养模版不能为空', trigger: 'change' }
        ],
        nextTime: [
          { required: true, validator: validateNextTime, trigger: 'change' }
        ],
        taskMode: [
          { required: true, message: '任务启动方式不能为空', trigger: 'change' }
        ],
        period: [
          { required: true, validator: period, trigger: 'change' }
        ],
        periodUnit: [
          { required: true, message: '周期单位不能为空', trigger: 'change' }
        ],
        maintenanceId: [
          { required: true, message: '维保班组不能为空', trigger: 'change' }
        ],
        maintainPersonId: [
          { required: true, message: '保养人员不能为空', trigger: 'change' }
        ],
        level: [
          { required: true, message: '保养级别不能为空', trigger: 'change' }
        ],
        startTime: [
          { required: true, validator: validateStartTime, trigger: 'change' }
        ],
        endTime: [
          { validator: validateEndTime, trigger: 'change' }
        ],
        remind: [
          { validator: remind, trigger: 'change' }
        ],
        timeOutNumber: [
          { validator: timeOutNumber, trigger: 'change' }
        ],
        status: [
          { required: true, message: '计划状态不能为空', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    if (!this.id) { // 没有id就是新增
      this.isShow = true
      this.loading = false
      Object.keys(this.defaultValue).forEach(key => { // 给右边数据赋值
        this.formData[key] = this.defaultValue[key]
      })
    } else { // 有id就是编辑
      this.getInfo()
    }
  },
  mounted() {
    this.getList()
    this.loadPeoples()
    this.loadTeam()
  },
  methods: {
    changePeriodUnit(e) {
      if (e == '日') {
        this.maxNumber = 6
      } else if (e == '周') {
        this.maxNumber = 4
      } else if (e == '月') {
        this.maxNumber = 2
      } else if (e == '季') {
        this.maxNumber = 3
      } else {
        this.maxNumber = 99999
      }
      this.formData.period = this.formData.period > this.maxNumber ? this.maxNumber : this.formData.period
    },
    getInfo() {
      getInfo(this.id).then(res => {
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          this.formData[key] = res.data[key]
          this.formData.maintenanceId = res.data.maintenanceId
          this.loadPeoples()
          this.loadTeam()
        })
        this.isShow = true
        this.loading = false
      })
    },
    getList() {
      list({ status: 1 }).then(res => {
        this.templateList = res.data
      })
      getEquipmentList({
        status: 1
      }).then(res => {
        this.equipmentList = res.data
      })
    },
    // 根据保养人员id查询维保班组
    searchTeam(e) {
      this.peopleList.forEach(item => {
        if (item.userId == e) {
          this.formData.maintenanceId = item.maintenanceId
        }
      })
    },
    // 加载维保班组数据
    loadTeam() {
      maintenanceTeamList({ status: 1 }).then(res => {
        this.teamList = res.data
      })
    },
    // 加载保养人员数据
    loadPeople() {
      this.formData.maintainPersonId = ''
      personnellist({
        maintenanceId: this.formData.maintenanceId,
        status: 1,
        maintenanceStatus: 1
      }).then(res => {
        this.peopleList = res.data
      })
    },
    // 加载保养人员数据
    loadPeoples() {
      personnellist({
        maintenanceId: this.formData.maintenanceId,
        status: 1,
        maintenanceStatus: 1
      }).then(res => {
        this.peopleList = res.data
      })
    },
    // 选择保养模板
    chooseTemplates() {
      this.$layer.iframe({// 弹框
        content: {
          content: chooseTemplate, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            id: this.formData.templateId ? this.formData.templateId : '',
            name: this.formData.templateName ? this.formData.templateName : ''
          }// props
        },
        area: ['1200px', '600px'],
        title: '选择保养模版', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // 选择保养设备
    chooseEquipments() {
      this.$layer.iframe({// 弹框
        content: {
          content: chooseEquipment, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            bookId: this.formData.bookId ? this.formData.bookId : ''
          }// props
        },
        area: ['1200px', '600px'],
        title: '选择保养设备', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // 选择维保班组和人员
    chooseTeamAndPeople() {
      this.$layer.iframe({// 弹框
        content: {
          content: chooseTeam, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            // teamId: this.formData.maintenanceId ? this.formData.maintenanceId : '',
            userId: this.formData.maintainPersonId ? this.formData.maintainPersonId : ''
          }// props
        },
        area: ['1200px', '600px'],
        title: '选择保养人员', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // 选择人员和班组返回id
    showTeamAndPeople(teamId, row, peopleId, num) {
      this.formData.maintenanceId = teamId
      this.loadTeam()
      this.loadPeoples()
      this.$nextTick(() => {
        if (peopleId) {
          this.formData.maintainPersonId = peopleId
          this.formData.checkPersonName = row.realName
        }
      })
    },
    // 提交
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          addOrUpdate({ ...this.formData, isAdd: true }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },
    // 获取保养模版id
    showTemplate(data) {
      console.log(data)
      this.formData.templateId = data.id
      this.formData.templateName = data.code + '/' + data.name
      this.getList()
    },
    // 获取保养设备id
    showEquipment(data) {
      this.formData.bookId = data.id
      this.formData.bookName = data.code + '/' + data.name
      this.getList()
    }
  }
}
</script>

<style lang="less" scoped>
.number_input{
  display: flex;
  flex-direction: row;
  align-content: flex-start;
  align-items: center;
  .unit{
    margin-left: 10px;
    color: #606266;
  }
}
</style>
